package router

import (
	"net/http"
	"strings"

	"GinAdmin/api"
	"GinAdmin/core/middleware"
	"GinAdmin/docs"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
)

// InitRouter 初始化路由
func InitRouter(mode string) *gin.Engine {
	// 设置gin模式
	gin.SetMode(mode)

	r := gin.New()
	r.Use(gin.Recovery())
	r.Use(middleware.Logger())

	// 跨域配置
	r.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Content-Type", "Authorization"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))

	// 静态文件
	r.StaticFS("/static", http.Dir("./static"))

	// Swagger文档
	docs.SwaggerInfo.BasePath = ""
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	// 健康检查
	r.GET("/health", func(c *gin.Context) {
		c.JSON(200, gin.H{"status": "ok"})
	})

	// API分组
	apiGroup := r.Group("/api")

	// 认证相关
	authAPI := api.NewAuthAPI()
	apiGroup.POST("/auth/login", authAPI.Login)
	apiGroup.POST("/auth/register", authAPI.Register)

	// 需要认证的API
	apiAuthGroup := apiGroup.Group("")
	apiAuthGroup.Use(middleware.JWTAuth())
	{
		// 用户相关API
		userAPI := api.NewUserAPI()
		apiAuthGroup.GET("/users", userAPI.GetUserList)
		apiAuthGroup.GET("/users/:id", userAPI.GetUserByID)
		apiAuthGroup.POST("/users", userAPI.CreateUser)
		apiAuthGroup.PUT("/users/:id", userAPI.UpdateUser)
		apiAuthGroup.DELETE("/users/:id", userAPI.DeleteUser)
		apiAuthGroup.GET("/users/profile", userAPI.GetUserProfile)
		apiAuthGroup.PUT("/users/profile", userAPI.UpdateUserProfile)
		apiAuthGroup.PUT("/users/password", userAPI.ChangePassword)

		// 角色相关API
		roleAPI := api.NewRoleAPI()
		apiAuthGroup.GET("/roles", roleAPI.GetRoleList)
		apiAuthGroup.GET("/roles/:id", roleAPI.GetRoleByID)
		apiAuthGroup.POST("/roles", roleAPI.CreateRole)
		apiAuthGroup.PUT("/roles/:id", roleAPI.UpdateRole)
		apiAuthGroup.DELETE("/roles/:id", roleAPI.DeleteRole)
		apiAuthGroup.GET("/roles/:id/menus", roleAPI.GetRoleMenus)
		apiAuthGroup.PUT("/roles/:id/menus", roleAPI.UpdateRoleMenus)

		// 菜单相关API
		menuAPI := api.NewMenuAPI()
		apiAuthGroup.GET("/menus", menuAPI.GetMenuList)
		apiAuthGroup.GET("/menus/tree", menuAPI.GetMenuTree)
		apiAuthGroup.GET("/menus/:id", menuAPI.GetMenuByID)
		apiAuthGroup.POST("/menus", menuAPI.CreateMenu)
		apiAuthGroup.PUT("/menus/:id", menuAPI.UpdateMenu)
		apiAuthGroup.DELETE("/menus/:id", menuAPI.DeleteMenu)
		apiAuthGroup.GET("/menus/user", menuAPI.GetUserMenus)

		// 部门相关API
		deptAPI := api.NewDepartmentAPI()
		apiAuthGroup.GET("/departments", deptAPI.GetDepartmentList)
		apiAuthGroup.GET("/departments/tree", deptAPI.GetDepartmentTree)
		apiAuthGroup.GET("/departments/:id", deptAPI.GetDepartmentByID)
		apiAuthGroup.POST("/departments", deptAPI.CreateDepartment)
		apiAuthGroup.PUT("/departments/:id", deptAPI.UpdateDepartment)
		apiAuthGroup.DELETE("/departments/:id", deptAPI.DeleteDepartment)

		// 消息相关API
		messageAPI := api.NewMessageAPI()
		apiAuthGroup.GET("/messages", messageAPI.GetMessageList)
		apiAuthGroup.GET("/messages/:id", messageAPI.GetMessageByID)
		apiAuthGroup.POST("/messages", messageAPI.CreateMessage)
		apiAuthGroup.PUT("/messages/:id", messageAPI.UpdateMessage)
		apiAuthGroup.PUT("/messages/:id/read", messageAPI.ReadMessage)
		apiAuthGroup.DELETE("/messages/:id", messageAPI.DeleteMessage)

		// 设置相关API
		settingAPI := api.NewSettingAPI()
		apiAuthGroup.GET("/settings", settingAPI.GetSettingList)
		apiAuthGroup.GET("/settings/:key", settingAPI.GetSettingByKey)
		apiAuthGroup.POST("/settings", settingAPI.CreateSetting)
		apiAuthGroup.PUT("/settings/:key", settingAPI.UpdateSetting)
		apiAuthGroup.DELETE("/settings/:key", settingAPI.DeleteSetting)
	}

	// 无匹配路由
	r.NoRoute(func(c *gin.Context) {
		acceptStr := c.Request.Header.Get("Accept")
		if strings.Contains(acceptStr, "text/html") {
			c.JSON(http.StatusNotFound, gin.H{
				"code": 404,
				"msg":  "页面不存在",
			})
			return
		}
		c.JSON(http.StatusNotFound, gin.H{
			"code": 404,
			"msg":  "接口不存在",
		})
	})

	return r
}
